<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>智能温室风扇监控系统</title>
<!--    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.0/dist/sockjs.min.js"></script>-->
<!--    <script src="https://cdn.jsdelivr.net/npm/stompjs/lib/stomp.min.js"></script>-->

    <!-- 替换原有的CDN链接 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <style>
        .container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            font-family: Arial, sans-serif;
        }

        .status-card {
            background: #f5f5f5;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .status-item {
            display: flex;
            align-items: center;
            margin: 10px 0;
        }

        .status-label {
            width: 120px;
            font-weight: bold;
            color: #666;
        }

        .status-value {
            flex: 1;
        }

        .level-indicator {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 4px;
            color: white;
            background: #4CAF50;
        }

        .auto-mode-true { color: #2196F3; }
        .auto-mode-false { color: #FF5722; }

        .control-panel {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin-top: 15px;
        }

        .control-btn {
            padding: 8px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            background: #2196F3;
            color: white;
            transition: background 0.3s;
        }

        .control-btn:hover {
            background: #1976D2;
        }

        .history-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .history-table th,
        .history-table td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        .history-table th {
            background: #f5f5f5;
        }

        .error-message {
            color: #f44336;
            margin: 10px 0;
        }
    </style>
</head>
<body>
<div class="container">
    <!-- 连接状态 -->
    <div id="connection-status" class="status-card" style="background: #ffeeba;">
        连接状态: <span id="status-text">连接中...</span>
    </div>

    <!-- 实时状态显示 -->
    <div class="status-card">
        <h2>风扇实时状态 (ID: <span id="fan-id">-</span>)</h2>
        <div class="status-item">
            <div class="status-label">当前风速</div>
            <div class="status-value">
                <span id="current-level" class="level-indicator">-</span>
            </div>
        </div>
        <div class="status-item">
            <div class="status-label">工作模式</div>
            <div class="status-value">
                <span id="auto-mode">-</span>
            </div>
        </div>
        <div class="status-item">
            <div class="status-label">最后更新时间</div>
            <div class="status-value" id="last-update">-</div>
        </div>
    </div>

    <!-- 控制面板 -->
    <div class="status-card">
        <h2>手动控制</h2>
        <div class="control-panel">
            <button class="control-btn" onclick="controlFan(0)">关闭</button>
            <button class="control-btn" onclick="controlFan(1)">微风 (1档)</button>
            <button class="control-btn" onclick="controlFan(2)">中风 (2档)</button>
            <button class="control-btn" onclick="controlFan(3)">强风 (3档)</button>
        </div>
        <div id="control-error" class="error-message"></div>
    </div>

    <!-- 历史记录 -->
    <div class="status-card">
        <h2>操作记录
            <button onclick="loadHistory()" style="float:right; padding: 5px 10px;">刷新记录</button>
        </h2>
        <table class="history-table">
            <thead>
            <tr>
                <th>时间</th>
                <th>风速档位</th>
                <th>操作模式</th>
                <th>操作员</th>
            </tr>
            </thead>
            <tbody id="history-body">
            <tr><td colspan="4">正在加载历史记录...</td></tr>
            </tbody>
        </table>
    </div>
</div>

<script>
    let stompClient = null;
    let fanId = 0; // 当前风扇ID

    function connect() {
        const socket = new SockJS('http://localhost:8080/gsas/api/v1/environment/subscribe');
        stompClient = Stomp.over(socket);

        stompClient.connect({}, (frame) => {
            updateConnectionStatus(true, frame.headers['session-id']);

            // 订阅风扇状态更新
            stompClient.subscribe('/topic/fan-status', (message) => {
                const data = JSON.parse(message.body);
                updateStatusDisplay(data);
            });

            loadHistory();
        }, (error) => {
            updateConnectionStatus(false, error.headers.message);
        });
    }

    function updateConnectionStatus(isConnected, message) {
        const statusDiv = document.getElementById('connection-status');
        const statusText = document.getElementById('status-text');

        if(isConnected) {
            statusDiv.style.background = '#d4edda';
            statusText.innerHTML = `已连接 (会话ID: ${message})`;
        } else {
            statusDiv.style.background = '#f8d7da';
            statusText.innerHTML = `连接失败: ${message}`;
        }
    }


    function updateStatusDisplay(data) {
        document.getElementById('fan-id').textContent = data.fanId || '-';
        fanId = data.fanId;

        const speedElement = document.getElementById('current-level');
        speedElement.textContent = data.level;
        speedElement.style.background = getLevelColor(data.level );


        document.getElementById('auto-mode').textContent = data.isAuto ? "自动模式" : "手动模式";
        document.getElementById('auto-mode').className = data.isAuto ? 'auto-mode-true' : 'auto-mode-false';

        // 更新时间显示
        const updateTime = new Date(data.updateTime);
        document.getElementById('last-update').textContent =
            `${updateTime.toLocaleDateString()} ${updateTime.toLocaleTimeString()}`;

    }

    function getLevelColor(level) {
        const colors = ['#f44336', '#FF9800', '#4CAF50', '#2196F3'];
        return colors[level] || '#9E9E9E';
    }

    async function controlFan(level) {
        const errorDiv = document.getElementById('control-error');
        errorDiv.textContent = '';

        try {
            const response = await fetch(`/gsas/api/v1/device/fan/control`, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify({
                    fanId: fanId,
                    level: level.toString(),
                    is_auto: false
                })
            });

            if(!response.ok) throw new Error(`控制失败: ${response.statusText}`);

            const result = await response.json();
            if(result.code !== 200) throw new Error(result.message);

            console.log('风扇控制成功:', result);
        } catch (error) {
            errorDiv.textContent = error.message;
            console.error('控制出错:', error);
        }
    }

    async function loadHistory() {
        const tbody = document.getElementById('history-body');
        tbody.innerHTML = '<tr><td colspan="4">加载中...</td></tr>';

        try {
            const response = await fetch(`/gsas/api/v1/device/fan/history/${fanId}`);
            const data = await response.json();

            if(data.code === 200) {
                renderHistory(data.data);
            } else {
                throw new Error(data.message);
            }
        } catch (error) {
            tbody.innerHTML = `<tr><td colspan="4" style="color:red">加载失败: ${error.message}</td></tr>`;
        }
    }

    function renderHistory(records) {
        const tbody = document.getElementById('history-body');
        tbody.innerHTML = '';

        records.forEach(record => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${new Date(record.operatorTime).toLocaleString()}</td>
                <td><span style="background:${getLevelColor(record.level)};
                               color:white; padding:2px 5px; border-radius:3px">
                    ${record.level}档
                </span></td>
                <td>${record.isAuto ? '自动' : '手动'}</td>
                <td>${record.operatorId || '系统'}</td>
            `;
            tbody.appendChild(tr);
        });
    }

    connect();
</script>
</body>
</html>